<?php
namespace app\common\model;

use think\Model;

class UserToken extends Model
{
    /**
     * 登陆存token
     * @param $user_id
     * @param int $platform     //1就是h5登陆（h5端和微信公众号端），2就是微信小程序登陆，3是支付宝小程序，4是app，5是pc
     * @return array
     */
    public function setToken($user_id,$platform=1){

        $userModel = new User();
        $userInfo = $userModel->where(array('id'=>$user_id))->find();
        if($userInfo){
            $data['user_id'] = $user_id;
            $data['platform'] = $platform;
            $data['ctime'] = time();
            $data['expiry'] = time()+86400*30;//有效期30天
            $data['token'] = $this->algorithm($userInfo['id'],$userInfo['password'],$platform,$data['ctime']);
            $re = $this->insert($data);
            if($re >0){
                $where[] = ['expiry', '<', time()];
                $this->where($where)->delete();
                $result['data'] = $data['token'];
                return showOk($result);
            }else{
                return showErr('生成token失败');
            }
        }else{
            return showErr('用户不存在');
        }
    }

    public function delToken($token)
    {
        $result = array(
            'status' => false,
            'data' => '',
            'msg' => ''
        );
        //删除掉旧的token
        $where[] = ['token', 'eq', $token];
        if($this->where($where)->delete()){
            $result['status'] = true;
            return showOk();
        }
        return $result;
    }


    /**
     * 根据token来获取用户的id
     * @param $token //token的值
     * @param int $status //用户状态，0是所有状态，1是取正常的用户状态
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkToken($token, $status = 1)
    {
        if(!$token)
        {
            return error_code(14006);
        }

        $where[] = ['token', 'eq', $token];
        $where[] = ['expiry', 'gt', time()];     //有效期180天
        $tokenInfo = $this->where($where)->find();
        if($tokenInfo){
            $userModel = new User();
            $where1[] = ['id','eq', $tokenInfo['user_id']];
            $userInfo = $userModel->where($where1)->find();
            if(!$userInfo){
                return error_code(11004);
            }
            if($status == 1 && $userInfo['status'] != 1){
                return error_code(11022);
            }

            return showOk(['data'=>$tokenInfo->toArray()]);
        }else{
            return showErr('不是有效的token,请重新登录！',14007);
        }

    }
    private function algorithm($user_id,$password,$platform,$createtime){
        return md5(md5($user_id.$password.$platform.$createtime).rand(1,10000));
    }
}